﻿using BalanceControl.Comm.Codec;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BalanceControl.Comm
{
    public class SerialHandler
    {
        public Action<byte[]> DataReceived { get; set; }
        public Action<byte[]> FrameReceived { get; set; }

        private SerialPort mSerialPort;
        private ICodec mCodec;

        public SerialHandler()
        {
            mSerialPort = new SerialPort();
            mSerialPort.DataReceived += SerialPort_DataReceived;
            mCodec = new FixLengthWithHeaderCodec(7);
        }

        public bool IsConnect
        {
            get
            {
                return mSerialPort.IsOpen;
            }
        }


        public bool Connect(string portName, int baudRate)
        {
            mSerialPort.PortName = portName;
            mSerialPort.BaudRate = baudRate;
            return Connect();
        }

        public bool Connect()
        {
            try
            {
                mSerialPort.Open();
                if (mSerialPort.IsOpen)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"串口连接失败:{ex.Message}");
            }
            return false;
        }

        public bool DisConnect()
        {
            if (mSerialPort.IsOpen)
            {
                mSerialPort.Close();
                return true;
            }
            return false;
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int readlen = mSerialPort.BytesToRead;
            if (readlen > 0)
            {
                byte[] tempBuffer = new byte[readlen];
                int count = mSerialPort.Read(tempBuffer, 0, readlen);
                if (count > 0)
                {
                    List<Object> result = mCodec.decode(new List<Object>() { tempBuffer });
                    if (result != null && result.Count > 0)
                    {
                        foreach (Object obj in result)
                        {
                            if (obj is byte[])
                            {
                                byte[] frame = obj as byte[];
                                FrameReceived?.Invoke(frame);
                            }
                        }
                    }
                    DataReceived?.Invoke(tempBuffer);
                }
            }
        }

        public void Transmit(byte[] data)
        {
            if (mSerialPort.IsOpen)
            {
                mSerialPort.Write(data, 0, data.Length);
            }
        }
    }
}
